package com.ting.log.config;

import com.alibaba.fastjson.JSONObject;
import com.ting.common.utils.HttpUtils;
import com.ting.log.bo.LogPositionBo;
import com.ting.log.dto.LogPositionDto;
import com.ting.log.handler.LogHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * @author zifang
 */
@Configuration
@Slf4j
public class LogBeanInit {

    @Bean
    @ConditionalOnMissingBean(LogHandler.class)
    public LogHandler logHandler() {
        log.warn("使用默认实现 LogHandler ...");
        return new LogHandler(){
            @Override
            public LogPositionBo ipToPosition(LogPositionDto logPositionDto) {
                Map<String,String> headerMap = new HashMap<>();
                headerMap.put("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0");
                headerMap.put("origin","https://www.baidu.com");
                headerMap.put("host","ifu-api.baidubce.com");
                headerMap.put("referer","https://www.baidu.com/s?wd=" + logPositionDto.getIp());
                headerMap.put("origin","https://www.baidu.com");
                String res = HttpUtils.get("https://qifu-api.baidubce.com/ip/geo/v1/district?ip=" + logPositionDto.getIp());
                JSONObject jsonObject = JSONObject.parseObject(res).getJSONObject("data");
                LogPositionBo logPositionBo = new LogPositionBo();
                logPositionBo.setIp(logPositionDto.getIp());
                logPositionBo.setPosition(jsonObject.getString("prov")+jsonObject.getString("city")+jsonObject.getString("district"));
                return logPositionBo;
            }
        };
    }

}
